//using UnityEngine;
//using System;
//using System.Collections;
//using System.Collections.Generic;
//using System.IO;
//using Bola.Extensions;
//using Pathfinding.Serialization.JsonFx;
//using System;
//using Disney.DMOAnalytics;
//
//public class PVPController {
//
//	private ScreenManager screenManager;
//	private PVPScreen pvpScreen;
//	private IBolaUser bolaUser;
//	EconomyController economyController;
//	private IGameSettings gameSettings;
//	private HTTPClient httpClient;
//	private IPipe bePipe;
//	private FacebookController facebookController;
//	private PvPRewardsCatalog pvpRewardCatalog;
//
//	RewardsModel winReward;
//	RewardsModel loseReward;
//
//	GameplayClub rivalTeam;
//	ReducedClubModel [] rivals;
//	int rivalArrayID;
//
//	public PVPController(ScreenManager screenManager,
//	                            IBolaUser bolaUser,
//	                     		EconomyController economyController,
//					            IGameSettings gameSettings,
//					            ShopsScreenController shopsScreenController,
//	                            HTTPClient httpClient,
//	                     		IPipe backendPipe,
//								PvPRewardsCatalog pvpRewardCatalog)
//	{
//		this.screenManager = screenManager;
//		this.bolaUser = bolaUser;
//		this.httpClient = httpClient;
//		this.bePipe = backendPipe;
//		this.pvpRewardCatalog = pvpRewardCatalog;
//		facebookController = new FacebookController();
//		SceneLoader.Instance.AddPersistentInfo (Constants.PINFO_FACEBOOK_CONTROLLER, facebookController);
//		this.gameSettings = gameSettings;
//		this.economyController = economyController;
//	}
//
//	public void OpenPVP()
//	{		
//		if (facebookController == null)
//		{
//			facebookController = (FacebookController)(SceneLoader.Instance.GetPersistentInfo (Constants.PINFO_FACEBOOK_CONTROLLER));
//			
//			if (facebookController == null)
//			{
//				facebookController = new FacebookController();
//				SceneLoader.Instance.AddPersistentInfo (Constants.PINFO_FACEBOOK_CONTROLLER, facebookController);				
//			}
//		}
//
//		if (Application.internetReachability != NetworkReachability.NotReachable || bolaUser.UserToken == "" || bolaUser.GameID == "")
//		{		
//		#if UNITY_IPHONE || UNITY_ANDROID
//			if (facebookController != null && facebookController.IsLogged ())
//			{
//				facebookController.GetMe();
//				facebookController.GetFacebookFriends ();
//			}
//		#endif
//			BindScreen();
//		}
//		else
//		{
//			GenericPopup.Instance.ShowPopupOk("NoInternet", () => {}, true);	
//		}
//	}
//	
//	private void BindScreen()
//	{
//		bool binded = pvpScreen != null;
//
//		pvpScreen = (PVPScreen)screenManager.PushScreen(ScreenNames.PVPScreen, ScreenTransitions.TransType.None, ScreenTransitions.TransType.FadeOutTransition);
//		pvpScreen.SetUserClubData(bolaUser.GameplayClub);
//		//pvpScreen.SetEnergyCost(gameSettings.PvPMatchCost.Energy);
//		pvpScreen.lblOpponent.text = "";
//
//		GetRandomTeam();
//		economyController.ShowHud ("PrematchTitle",false, true);
//		if (!binded)
//		{
//			Debug.Log("BINDING");
//			pvpScreen.OnPlayMatchEvent += EnterMatch;
//			pvpScreen.OnConnectFacebookEvent += FacebookLogIn;
//			pvpScreen.OnBackToMenuEvent += BackToMainMenu;		
//			pvpScreen.OnNextOpponentEvent += GetNewRandomTeam;		
//			pvpScreen.OnNextCategoryEvent += OnNextCategoryAction;
//			pvpScreen.OnPrevCategoryEvent += OnPrevCategoryAction;		
//			pvpScreen.OnScreenEntered += () => { economyController.ShowHud ("PrematchTitle",false, true); };
//			pvpScreen.OnScreenExited += () => { economyController.HideHud (); };	
//			pvpScreen.buttonConnect.collider.enabled = true;
//		}
//		LoggingIn = false;
//		pvpScreen.ConfigueCostOpponent(gameSettings.PVPSkipPrice.Bolars,true);
//		ActionFacebookConnect();
//	}
//
//	private void FacebookUserConnected()
//	{				
//		#if UNITY_IPHONE || UNITY_ANDROID
//		GenericPopup.Instance.ShowPopupOk("FacebookUserCheck", ()=>{}, false,true);
//		facebookController.GetFacebookFriends ();
//		facebookController.graphRequestCompletedEvent += GetFirendsCallbackSuccess;
//
//		//facebookController.Post("I AM PLAYING BOLA!!!");
//		pvpScreen.buttonConnect.SetActive(false);
//		pvpScreen.IsConectedForApp = true;
//		#endif
//	}
//	public void ActionFacebookConnect()
//	{
//		#if UNITY_IPHONE || UNITY_ANDROID
//		if (facebookController.IsLogged())
//		{
//			Debug.Log("FACE ID NOT LOADED:" + bolaUser.FacebookID);
//			if (facebookController._Me != null)
//			{
//				Debug.Log("FACE ID LOADED:" + facebookController._Me.id);
//				if (bolaUser.FacebookID == facebookController._Me.id && bolaUser.FacebookID != "" && bolaUser.FacebookID != null)
//				{
//					Debug.Log("ENTER A");
//					FacebookUserConnected();
//				}
//				else
//				{
//					Debug.Log("ENTER B");
//					CheckFacebookUser();
//				}
//
//				// DMO Tracking user_info: Login con redes sociales Facebook, Twitter, etc...
//				#if !UNITY_EDITOR
//				try 
//				{
//					Dictionary <string,string> userInfoData = new Dictionary <string,string> ();
//
//					string gameID = (bolaUser.GameID != null) ? bolaUser.GameID : string.Empty;
//
//					userInfoData.Add ("user_id",  gameID);	// String
//					userInfoData.Add ("user_id_domain", "facebook.com");			// String
//					DMOAnalytics.SharedAnalytics.LogAnalyticsEventWithContext ("user_info", userInfoData);
//				}
//				catch (System.Exception exception) 
//				{
//					Debug.Log("DMO Analytics Error:" + exception.ToString());
//				}
//				#endif
//			}
//			else
//			{
//				Debug.Log("Get ME");
//				GenericPopup.Instance.ShowPopupOk("FacebookUserCheck", ()=>{}, false);
//				facebookController.GetMe();
//
//				facebookController.CleanGraphActions ();
//				facebookController.graphRequestCompletedEvent += GetMeCallbackSuccess;
//				facebookController.graphRequestFailedEvent += GraphRequestedFailed;
//				//pvpScreen.OnUpdate += CheckIfLogged;
//			}
//		}else
//		{
//			pvpScreen.friendPic.gameObject.SetActive(false);
//		}
//		#endif
//	}
//	
//	private void CheckFacebookUser()
//	{				
//		GenericPopup.Instance.ShowPopupOk("FacebookUserCheck", () => {}, false);
//		GetUser();
//	}
//
//	BolaUserModel tempBolaUser;
//	private void CheckFacebookIDinBE()
//	{				
//		GenericPopup.Instance.ShowPopupConfirmation("PopupRepetedFaceID", GetUserClub, PostNewUserClub);
//	}
//
//	private void UserPostSuccess(string faceID)
//	{
//		bolaUser.SetFacebookID(faceID);
//		GenericPopup.Instance.HidePopup();
//		Debug.LogWarning("FACE POST COMPLETE:" + faceID);
//	}
//	
//	private void UserPostFail()
//	{
//		Debug.LogWarning("Cannot create new user");
//		GenericPopup.Instance.HidePopup();
//	}
//
//	public void BackToMainMenu()
//	{
//		pvpScreen.OnNextOpponentEvent -= GetNextFacebookTeam;
//		pvpScreen.OnNextOpponentEvent -= GetNewRandomTeam;	
//
//		if (pvpScreen.GetCategory () != PVPScreen.Categories.Rivals)
//			pvpScreen.OnPlayMatchEvent -= EnterMatch;	
//		else
//			pvpScreen.OnPlayMatchEvent -= EnterRivalMatch;	
//		
//
//		screenManager.ExitScreen(false);
//	}
//
//	public PVPMatchInfo.PvpMatchType GetMatchType()
//	{		
//		PVPMatchInfo.PvpMatchType matchType = PVPMatchInfo.PvpMatchType.rivals;
//		if (pvpScreen.GetCategory () == PVPScreen.Categories.Friends)
//			matchType = PVPMatchInfo.PvpMatchType.facebook;
//		else if (pvpScreen.GetCategory () == PVPScreen.Categories.World)
//			matchType = PVPMatchInfo.PvpMatchType.world;
//		else if (pvpScreen.GetCategory () == PVPScreen.Categories.Rivals)
//			matchType = PVPMatchInfo.PvpMatchType.rivals;
//		return matchType;
//	}
//	
//	private void EnterRivalMatch()
//	{   
//		GenericPopup.Instance.ShowPopupOk("PopupEnterRivalMatch", ()=>{}, false);
//		
//		if(Application.internetReachability != NetworkReachability.NotReachable)
//		{
//			httpClient.Send (RequestFactory.GetRivalTeam(bolaUser.GameID, bolaUser.UserToken, rivals[rivalArrayID].clubId) ) 
//				.SetCompleteHandler(www => {
//					if(!www.TestEmptyResponse(www.text))
//					{
//						Debug.LogWarning("RIVALS TEAM:" + www.error + "Text: " + www.text);	
//
//						ClubModel randomTeam = JsonReader.Deserialize<ClubModel>(www.text);
//
//						GameplayClub opponent = new GameplayClub(randomTeam.ClubId, randomTeam.Name,
//						                                         randomTeam.Outfit, randomTeam.Team.CurrentFormation,
//						                                         randomTeam.Team.Players);
//						SetMatchInfo(opponent, bolaUser.Club.XP, randomTeam.XP);					
//						RivalMatchSuccess();
//						
//					}else{
//						RivalMatchFailed();
//					}
//				})
//					.SetErrorHandler(www => { 
//						Debug.Log("RIVALS  WWW error: "+www.error);
//						RivalMatchFailed();
//					} 
//					);
//		}else{
//			RivalMatchFailed();
//		}
//	}	
//	private void RivalMatchSuccess()
//	{
//		GenericPopup.Instance.HidePopup();
//		EnterMatch ();
//		Debug.LogWarning("rivals match configured");
//	}
//	private void RivalMatchFailed()
//	{
//		Debug.LogWarning("Cannot play match");
//		pvpScreen.PrevCategory ();
//		GenericPopup.Instance.HidePopup();
//	}
//
//	private void EnterMatch()
//	{   
//#if UNITY_IPHONE || UNITY_ANDROID
//		if (pvpScreen.GetCategory () == PVPScreen.Categories.Friends && !facebookController.IsLogged ())
//			return;	
//		
//		if (pvpScreen.GetCategory () == PVPScreen.Categories.Friends && facebookController.IsLogged () && !canPlayFacebookMatch)
//			return;	
//#endif
//		economyController.CheckEnergy (gameSettings.PvPMatchCost.Energy, () => {
//			PVPMatchInfo matchConfiguration = new PVPMatchInfo(GetMatchType() == PVPMatchInfo.PvpMatchType.facebook ? bolaUser.FacebookGameplayClub : bolaUser.GameplayClub, 
//			                                                   rivalTeam, 
//			                                                   gameSettings.PvPMatchCost.Energy, 
//			                                                   winReward, 
//			                                                   loseReward, 
//			                                                   GetMatchType(),
//			                                                   facebookController);
//			
//			SceneLoader.Instance.AddPersistentInfo (Constants.PINFO_PVP_MATCH, matchConfiguration);
//			SceneLoader.Instance.LoadScene (Constants.SCENE_PLAY);
//		
//		});
//
//	}
//	
//	private void OnNextCategoryAction()
//	{
//		moveNext = true;
//		if (pvpScreen.GetCategory () == PVPScreen.Categories.Friends)
//		{		
//			pvpScreen.OnPlayMatchEvent -= EnterRivalMatch;
//			pvpScreen.OnPlayMatchEvent += EnterMatch;
//
//			pvpScreen.OnNextOpponentEvent -= GetNextRival;
//			pvpScreen.OnPrevOpponentEvent -= GetPrevRival;
//
//			pvpScreen.OnNextOpponentEvent += GetNextFacebookTeam;
//			pvpScreen.OnPrevOpponentEvent += GetPrevFacebookTeam;	
//#if UNITY_IPHONE || UNITY_ANDROID
//			Debug.Log("real log: " + facebookController.IsLogged() + " & App log: " + pvpScreen.IsConectedForApp);
//			if (!facebookController.IsLogged()|| !pvpScreen.IsConectedForApp)
//			{
//				pvpScreen.ShowOpponentsArrows(false);
//				pvpScreen.friendPic.gameObject.SetActive(false);
//				pvpScreen.noTeamSelected.gameObject.SetActive(true);
//			}
//			else
//			{
//				pvpScreen.buttonConnect.SetActive(false);
//				GetNextFacebookTeam();
//                //UpdateFacebookVisual();
//			}
//			#endif
//		}
//		else if (pvpScreen.GetCategory () == PVPScreen.Categories.World)
//		{
//			GetRandomTeam();
//			pvpScreen.OnNextOpponentEvent -= GetNextFacebookTeam;
//			pvpScreen.OnPrevOpponentEvent -= GetPrevFacebookTeam;
//			
//			pvpScreen.OnNextOpponentEvent += GetNewRandomTeam;
//
//			//Configure cost of next opponent
//			pvpScreen.ConfigueCostOpponent(gameSettings.PVPSkipPrice.Bolars, true);
//		}
//		else if (pvpScreen.GetCategory () == PVPScreen.Categories.Rivals)
//		{			
//			GetRivalsList ();
//
//			pvpScreen.OnPlayMatchEvent += EnterRivalMatch;
//			pvpScreen.OnPlayMatchEvent -= EnterMatch;
//
//			pvpScreen.OnNextOpponentEvent -= GetNewRandomTeam;
//			
//			pvpScreen.OnNextOpponentEvent += GetNextRival;
//			pvpScreen.OnPrevOpponentEvent += GetPrevRival;
//
//			pvpScreen.ShowOpponentsArrows(true);
//			pvpScreen.lblOpponent.text = "";
//		}
//	}
//	
//	private void OnPrevCategoryAction()
//	{
//		moveNext = false;
//		if (pvpScreen.GetCategory () == PVPScreen.Categories.Friends)
//		{
//			pvpScreen.OnNextOpponentEvent -= GetNewRandomTeam;
//
//			pvpScreen.OnNextOpponentEvent += GetNextFacebookTeam;
//			pvpScreen.OnPrevOpponentEvent += GetPrevFacebookTeam;
//#if UNITY_IPHONE || UNITY_ANDROID
//			Debug.Log("real log: " + facebookController.IsLogged() + " & App log: " + pvpScreen.IsConectedForApp);
//			if (!facebookController.IsLogged() || !pvpScreen.IsConectedForApp)
//			{
//				pvpScreen.ShowOpponentsArrows(false);
//				pvpScreen.friendPic.gameObject.SetActive(false);
//				pvpScreen.noTeamSelected.gameObject.SetActive(true);
//			}
//			else{				
//				pvpScreen.buttonConnect.SetActive(false);
//				GetNextFacebookTeam();
//			}
//			#endif
//		}
//		else if (pvpScreen.GetCategory () == PVPScreen.Categories.Rivals)
//		{			
//			GetRivalsList ();			
//
//			pvpScreen.OnPlayMatchEvent += EnterRivalMatch;
//			pvpScreen.OnPlayMatchEvent -= EnterMatch;
//
//			pvpScreen.OnNextOpponentEvent -= GetNextFacebookTeam;
//			pvpScreen.OnPrevOpponentEvent -= GetPrevFacebookTeam;
//			
//			pvpScreen.OnNextOpponentEvent += GetNextRival;
//			pvpScreen.OnPrevOpponentEvent += GetPrevRival;
//			
//			pvpScreen.ShowOpponentsArrows(true);
//		}
//		else if (pvpScreen.GetCategory () == PVPScreen.Categories.World)
//		{		
//			GetRandomTeam();				
//			pvpScreen.OnPlayMatchEvent -= EnterRivalMatch;
//			pvpScreen.OnPlayMatchEvent += EnterMatch;
//
//			pvpScreen.OnNextOpponentEvent -= GetNextRival;
//			pvpScreen.OnPrevOpponentEvent -= GetPrevRival;
//
//			pvpScreen.OnNextOpponentEvent += GetNewRandomTeam;
//
//			//Configure cost of next opponent
//			pvpScreen.ConfigueCostOpponent(gameSettings.PVPSkipPrice.Bolars, true);
//		}
//	}		
//	
//	public void SetMatchInfo(GameplayClub opponent, int userXp, int opponentXP)
//	{
//		rivalTeam = opponent;
//		winReward = RewardScalator(gameSettings.PvPReward, GetRewardDifficultyMultiplier(userXp,opponentXP), gameSettings.PvPRewardChallengerWin);
//		loseReward = RewardScalator(gameSettings.PvPReward, GetRewardDifficultyMultiplier(userXp,opponentXP),  gameSettings.PvPRewardChallengerDraw);
//		pvpScreen.SetOpponentData(opponent, winReward.Gold, winReward.Bolars);
//	}
//
//	private void SendFacebookUserID(string faceID)
//	{
//		GenericPopup.Instance.ShowPopupOk("PopupMessagePostUser", ()=>{}, false);
//		
//		if(Application.internetReachability != NetworkReachability.NotReachable)
//		{
//			httpClient.Send (RequestFactory.SetFaceUserRequest(bolaUser.GameID, bolaUser.UserToken, faceID) ) 
//				.SetCompleteHandler(www => {
//					if(!www.TestEmptyResponse(www.text))
//					{
//						Debug.Log ("FACE ID POSTED:"+ www.text);						
//						UserPostSuccess(faceID);
//						
//					}else{
//						UserPostFail();
//					}
//				})
//					.SetErrorHandler(www => { 
//						Debug.Log("FACEPOST  WWW error: "+www.error);
//						UserPostFail();
//					} 
//					);
//		}else{
//			UserPostFail();
//		}
//	}
//	
//	class RandomOponentResponse
//	{
//		[JsonName("opponent")]
//		public ClubModel club;
//		public RandomOponentResponse () 
//		{
//		}
//	}
//	
//	void GetNextRival()
//	{
//		rivalArrayID++;
//		if (rivalArrayID == rivals.Length )
//			rivalArrayID = 0;
//		
//		GameplayClub opponent = new GameplayClub(rivals[rivalArrayID].clubId,
//		                                         rivals[rivalArrayID].name,
//		                                         new OutfitModel(rivals[rivalArrayID].pattern, rivals[rivalArrayID].color1,rivals[rivalArrayID].color2,rivals[rivalArrayID].color3),
//		                                         bolaUser.Club.Team.CurrentFormation, //mocker, ovverrited after
//		                                         bolaUser.Club.Team.Players); //mocker, ovverrited after
//		SetMatchInfo(opponent, bolaUser.Club.XP, rivals[rivalArrayID].xp);
//	}	
//	void GetPrevRival()
//	{
//		rivalArrayID--;
//		if (rivalArrayID == -1)
//			rivalArrayID = rivals.Length-1;
//		
//		GameplayClub opponent = new GameplayClub(rivals[rivalArrayID].clubId,
//		                                         rivals[rivalArrayID].name,
//		                                         new OutfitModel(rivals[rivalArrayID].pattern, rivals[rivalArrayID].color1,rivals[rivalArrayID].color2,rivals[rivalArrayID].color3),
//		                                         bolaUser.Club.Team.CurrentFormation, //mocker, ovverrited after
//		                                         bolaUser.Club.Team.Players); //mocker, ovverrited after
//		SetMatchInfo(opponent, bolaUser.Club.XP, rivals[rivalArrayID].xp);
//	}
//
//	public void GetRivalsList(bool success = true)
//	{
//		if (Application.internetReachability != NetworkReachability.NotReachable)
//		{
//			//always try to check with BE the sponsor contract status
//			httpClient.Send(RequestFactory.GetRivals(bolaUser.GameID, bolaUser.UserToken) )
//				.SetCompleteHandler(www =>
//				                    {
//					if (!www.TestEmptyResponse(www.text))
//					{
//						Debug.Log("RESPONSE: "+www.text);
//						if (www.text != "[]")
//						{
//							rivals =  JsonReader.Deserialize<ReducedClubModel[]>(www.text);
//							try{				
//								if (rivals.Length > 1)
//								{
//									pvpScreen.butonNextOpponent.SetActive(true);
//									pvpScreen.butonPrevOpponent.SetActive(true);
//								}
//								else
//								{
//									pvpScreen.butonNextOpponent.SetActive(false);
//									pvpScreen.butonPrevOpponent.SetActive(false);
//								}
//								GameplayClub opponent = new GameplayClub(rivals[rivalArrayID].clubId,
//								                                         rivals[rivalArrayID].name,
//								                                         new OutfitModel(rivals[rivalArrayID].pattern, rivals[rivalArrayID].color1,rivals[rivalArrayID].color2,rivals[rivalArrayID].color3),
//								                                         bolaUser.Club.Team.CurrentFormation, //mocker, ovverrited after
//								                                         bolaUser.Club.Team.Players); //mocker, ovverrited after
//								SetMatchInfo( opponent, bolaUser.Club.XP, rivals[rivalArrayID].xp);
//							}catch(Exception e)
//							{
//								Debug.LogError("NO SE PUEDE PARSEAR EL USER! !!");
//								GenericPopup.Instance.ShowPopupOk("PvpGetRivalsError", NoRivals, true);
//							}
//						}
//						else{
//							pvpScreen.DeactivateInput ();
//							NoRivals();
//						}
//					}
//					else
//					{
//						Debug.LogWarning("STATE Validation ERROR:" + www.error + "Text: " + www.text);
//						GenericPopup.Instance.ShowPopupOk("PvpGetRivalsError", NoRivals, true);
//					}
//				})
//					.SetErrorHandler(www =>
//					                 { 
//						Debug.LogWarning("STATE Validation ERROR:" + www.error + "Text: " + www.text);
//						GenericPopup.Instance.ShowPopupOk("PvpGetRivalsError", NoRivals, true);
//					} 
//					);
//		}
//		else
//		{
//			GenericPopup.Instance.ShowPopupOk("NoInternet", () => {}, true);
//		}
//	}
//	bool moveNext;
//	public void NoRivals()
//	{
//		if (!moveNext)
//			pvpScreen.PrevCategory ();
//		else
//			pvpScreen.NextCategory ();
//		pvpScreen.ActivateInput ();
//	}
//
//	public void GetRandomTeam(bool success = true)
//	{
//		if (Application.internetReachability != NetworkReachability.NotReachable)
//		{
//			//always try to check with BE the sponsor contract status
//			httpClient.Send(RequestFactory.GetRandomTeam(bolaUser.GameID, bolaUser.UserToken) )
//				.SetCompleteHandler(www =>
//				                    {
//					if (!www.TestEmptyResponse(www.text))
//					{
//						RandomOponentResponse randomTeam = JsonReader.Deserialize<RandomOponentResponse>(www.text);
//						Debug.Log("RESPONSE: "+www.text);
//						try{
//						GameplayClub opponent = new GameplayClub(randomTeam.club.ClubId, randomTeam.club.Name,
//						                                         randomTeam.club.Outfit, randomTeam.club.Team.CurrentFormation,
//						                                         randomTeam.club.Team.Players);
//						SetMatchInfo(opponent, bolaUser.Club.XP, randomTeam.club.XP);
//						}catch(Exception e)
//						{
//							Debug.LogError("NO SE PUEDE PARSEAR EL USER! ARREGLAR!!");
//							Debug.LogError("Fuerzo esto temporalmente!! pero esta muy mal");
//							pvpScreen.DeactivateInput();
//							GenericPopup.Instance.ShowPopupOk("PvpGetOpponentError", GetRandomTeamError, true);
//						}
//					}
//					else
//					{
//						Debug.LogWarning("STATE Validation ERROR:" + www.error + "Text: " + www.text);
//						pvpScreen.DeactivateInput();
//						GenericPopup.Instance.ShowPopupOk("PvpGetOpponentError", GetRandomTeamError, true);
//					}
//				})
//					.SetErrorHandler(www =>
//					                 { 
//						Debug.LogWarning("STATE Validation ERROR:" + www.error + "Text: " + www.text);
//						pvpScreen.DeactivateInput();
//						GenericPopup.Instance.ShowPopupOk("PvpGetOpponentError", GetRandomTeamError, true);
//						} 
//				);
//		}
//		else
//		{
//			GenericPopup.Instance.ShowPopupOk("NoInternet", () => {}, true);
//		}
//	}
//
//	void GetRandomTeamError()
//	{
//		pvpScreen.ActivateInput();
//		BackToMainMenu();
//	}
//	
//	public void GetNewRandomTeam()
//	{
//		GenericPopup.Instance.ShowPopupConfirmation("ChangeRival", GetNewRandomTeamConfirmation, () => {}); //RejectMyFacebookTeam);
//	}
//	
//	public void GetFirendsCallbackSuccess()
//	{
//		#if UNITY_IPHONE || UNITY_ANDROID
//		Debug.Log("GetFriendsCallbackSuccess");	
//		FacebookAppFriend myFriend = facebookController.GetNextFriend ();
//		if (myFriend != null)
//		{
//			if (pvpScreen.GetCategory () == PVPScreen.Categories.Friends)
//			{
//				pvpScreen.lblOpponent.gameObject.SetActive(true);
//				pvpScreen.lblOpponent.text = myFriend.name;
//				pvpScreen.friendPic.gameObject.SetActive (true);
//				pvpScreen.friendPic.LoadLocalImage("facebookFriends", myFriend.id, "https://graph.facebook.com/"+ myFriend.id +"/picture?width=300&height=300",true, 10); 
//				pvpScreen.buttonConnect.SetActive(false);	
//				GetFacebookTeam(myFriend.id);
//			}
//		}
//		else
//		{				
//			if (pvpScreen.GetCategory () == PVPScreen.Categories.Friends)
//				GenericPopup.Instance.ShowPopupOk("NoFacebookFriends", CloseNoFriendsPopup, true);
//		}	
//		#endif
//	}
//	
//	public void GetMeCallbackSuccess()
//	{
//		Debug.Log("GetMeCallbackSuccess");	
//		
//		#if UNITY_IPHONE || UNITY_ANDROID
//		facebookController.graphRequestCompletedEvent -= GetMeCallbackSuccess;
//		#endif
//		
//		ActionFacebookConnect();		
//	}	
//	
//	public void GraphRequestedFailed()
//	{
//		Debug.Log("GraphRequestedFailed");	
//		GenericPopup.Instance.ShowPopupOk("FacebookError", NoRivals, true);
//	}
//
//	public void SuccesLogInCallback()
//	{
//		Debug.Log("SuccessLogInCallback");	
//		#if UNITY_IPHONE || UNITY_ANDROID
//		LoggingIn = false;
//		pvpScreen.buttonConnect.SetActive(false);
//		facebookController.GetMe ();
//		
//		facebookController.CleanGraphActions ();
//		facebookController.graphRequestCompletedEvent += GetMeCallbackSuccess;
//		facebookController.graphRequestFailedEvent += GraphRequestedFailed;
//		#endif
//	}
//	public void FailedLogInCallback(Prime31.P31Error err)
//	{		
//		Debug.Log("FailedLogInCallback");	
//		#if UNITY_IPHONE || UNITY_ANDROID
//		LoggingIn = false;
//		GenericPopup.Instance.ShowPopupOk("FacebookError", () => {pvpScreen.friendPic.gameObject.SetActive(false); pvpScreen.buttonConnect.SetActive(true); NoRivals ();}, true);
//		#endif
//	}
//
//	void CloseNoFriendsPopup ()
//	{
//#if UNITY_IPHONE || UNITY_ANDROID
//		facebookController.InvitePlayer ();
//#endif
//		pvpScreen.NextCategory ();
//		GenericPopup.Instance.HidePopup ();
//	}
//
//	public void GetNewRandomTeamConfirmation()
//	{
//		economyController.UseMoney (gameSettings.PVPSkipPrice.Bolars, gameSettings.PVPSkipPrice.Gold, () => 
//		{
//			bePipe.Pipe<SkipPost> (Constants.API_POST_SKIP, new SkipPost (true), GetRandomTeam);
//
//			// DMO Tracking in_app_currency_action: comprar oponente
//			#if !UNITY_EDITOR
//			
//			Dictionary <string,string> pvpBollars = new Dictionary <string,string> ();
//
//			string gameID = (bolaUser.GameID != null) ? bolaUser.GameID : string.Empty;
//			string gameClubXP = (bolaUser.Club != null && bolaUser.Club.XP != null) ? bolaUser.Club.XP.ToString() : string.Empty;
//
//			pvpBollars.Add ("player_id", gameID);
//			
//			if (gameSettings.PVPSkipPrice.Bolars != 0 && gameSettings.PVPSkipPrice.Gold == 0)
//			{
//				pvpBollars.Add ("currency", "Bollars");
//				pvpBollars.Add ("amount", "-" + gameSettings.PVPSkipPrice.Bolars.ToString ());
//			}
//			else if (gameSettings.PVPSkipPrice.Gold != 0 && gameSettings.PVPSkipPrice.Bolars == 0)
//			{
//				pvpBollars.Add ("currency", "Gold");
//				pvpBollars.Add ("amount", "-" + gameSettings.PVPSkipPrice.Gold.ToString ());
//			}
//			
//			pvpBollars.Add ("item", "opponent");
//			pvpBollars.Add ("type", "pvp");
//			pvpBollars.Add ("subtype", "pvp");
//			pvpBollars.Add ("context" , "pvpOpponent");
//			pvpBollars.Add ("level" , gameClubXP);
//			
//			DMOAnalytics.SharedAnalytics.LogAnalyticsEventWithContext ("in_app_currency_action", pvpBollars);
//			
//			#endif
//
//			#if (!UNITY_EDITOR) 
//			
//			// DMO 
//			Dictionary<string, string> newOpponentPVP = new Dictionary<string, string>();
//
//			gameID = (bolaUser.GameID != null) ? bolaUser.GameID : string.Empty;
//			gameClubXP = (bolaUser.Club != null && bolaUser.Club.XP != null) ? bolaUser.Club.XP.ToString() : string.Empty;
//
//			newOpponentPVP.Add("player_id",  gameID);
//			newOpponentPVP.Add("context", "PvP");
//			newOpponentPVP.Add("action", "NewOpponent");
//			newOpponentPVP.Add("level", gameClubXP);
//			
//			DMOAnalytics.SharedAnalytics.LogAnalyticsEventWithContext("game_action", newOpponentPVP);
//			
//			#endif
//		});
//	}
//
//	public void GetFacebookTeam(string teamID)
//	{
//		#if UNITY_IPHONE || UNITY_ANDROID
//		if (Application.internetReachability != NetworkReachability.NotReachable)
//		{
//			Debug.Log("FACE ID:" + bolaUser.FacebookID);
//			//always try to check with BE the sponsor contract status
//			httpClient.Send(RequestFactory.GetFacebookTeam(bolaUser.GameID, bolaUser.UserToken, teamID)) 
//				.SetCompleteHandler(www =>
//				                    {
//					if (!www.TestEmptyResponse(www.text))
//					{						
//						Debug.LogWarning("FACEBOOK TEAM Text: " + www.text);	
//						ClubModel randomTeam = JsonReader.Deserialize<ClubModel>(www.text);
//						GameplayClub opponent = new GameplayClub(teamID, randomTeam.Name,
//						                                         randomTeam.Outfit, randomTeam.Team.CurrentFormation,
//						                                         randomTeam.Team.Players);
//						SetMatchInfo(opponent,bolaUser.Club.XP, randomTeam.XP);						
//						UpdateFacebookVisual ();
//						canPlayFacebookMatch = true;
//					}
//					else
//					{
//						Debug.LogWarning("FACEBOOK Validation ERROR:" + www.error + "Text: " + www.text);	
//						GenericPopup.Instance.ShowPopupOk("NoInternet", () => {}, true);
//						GenericPopup.Instance.ShowPopupOk("FacebookFriendError", () => {FacebookFriendError(teamID);}, true);
//					}
//				})
//					.SetErrorHandler(www =>
//					                 { 
//						Debug.LogWarning("FACEBOOK Validation ERROR:" + www.error + "Text: " + www.text);
//						GenericPopup.Instance.ShowPopupOk("FacebookFriendError", () => {FacebookFriendError(teamID);}, true);
//					} 
//					);
//		}
//		else
//		{
//			GenericPopup.Instance.ShowPopupOk("NoInternet", () => {}, true);
//		}
//		#endif
//
//	}
//
//	bool canPlayFacebookMatch;
//	private void FacebookFriendError(string teamID)
//	{
//		#if UNITY_IPHONE || UNITY_ANDROID
//
//		facebookController.RemoveInvalidFriend(teamID); 		
//		pvpScreen.noTeamSelected.gameObject.SetActive(true);
//		canPlayFacebookMatch = false;
//		#endif
//	}
//	
//	public void GetUser()
//	{
//		if (Application.internetReachability != NetworkReachability.NotReachable)
//		{
//			#if UNITY_IPHONE || UNITY_ANDROID
//			//always try to check with BE the sponsor contract status
//			httpClient.Send(RequestFactory.GetBolaUser(bolaUser.GameID, bolaUser.UserToken, facebookController._Me.id)) 
//				.SetCompleteHandler(www =>
//				                    {
//					if (!www.TestEmptyResponse(www.text))
//					{	
//						Debug.Log("BOLA USER:"+www.error+" - text:" + www.text);	
//						tempBolaUser = JsonReader.Deserialize<BolaUserModel>(www.text);
//						GenericPopup.Instance.HidePopup ();
//						CheckFacebookIDinBE ();
//					}
//					else
//					{
//						Debug.Log("error:"+www.error+" - text:" + www.text);	
//						GenericPopup.Instance.HidePopup ();
//						GenericPopup.Instance.ShowPopupOk("FacebookError", () => {}, true);			
//					}
//				})
//					.SetErrorHandler(www =>
//					                 { 		
//						Debug.Log("error:"+www.error+" - text:" + www.text);
//						if (bolaUser.FacebookID != facebookController._Me.id)//if it is different, I have to check if it is empty, or really different
//						{
//							if (bolaUser.FacebookID == "" || bolaUser.FacebookID == null || bolaUser.FacebookID == string.Empty )//unauthorized, due to no ID and token related
//							{
//								GenericPopup.Instance.HidePopup ();			
//								bolaUser.SetFacebookID(facebookController._Me.id);
//								SendFacebookUserID(facebookController._Me.id);
//								FacebookUserConnected();
//							}
//							else
//							{
//								GenericPopup.Instance.HidePopup ();
//								GenericPopup.Instance.ShowPopupConfirmation("OtherFacebookAccount", NewBolaUser, FacebookLogOut);
//							}
//						}
//					} 
//					);
//				#endif
//		}
//		else
//		{
//			GenericPopup.Instance.ShowPopupOk("NoInternet", () => {}, true);
//		}
//	}	
//	
//	public void NewBolaUser()	
//	{	
//		FacebookLogOut ();
//		//Debug.LogError (Application.persistentDataPath);
//		//Debug.LogError (BolaUserModel.ExistLocalUser);
//		Directory.Delete (Application.persistentDataPath, true);
//		//Debug.LogError (BolaUserModel.ExistLocalUser);
//		ClearPlayerPrefs();
//		bolaUser.DeleteBolaUser();
//		//Debug.LogError (BolaUserModel.ExistLocalUser);
//		Application.LoadLevel (0);		
//	}
//
//	private void ClearPlayerPrefs()
//	{
//		PlayerPrefs.SetString(Constants.SPONSOR_IMG_LOGO,string.Empty);
//		PlayerPrefs.SetString(Constants.SPONSOR_IMG_BILLBOARD,string.Empty);
//		PlayerPrefs.SetString(Constants.SPONSOR_IMG_CENTERFIELD,string.Empty);
//		PlayerPrefs.SetString(Constants.SPONSOR_IMG_DAILYREWARD,string.Empty);
//		PlayerPrefs.SetString(Constants.SPONSOR_IMG_SHIRT,string.Empty);
//		
//		PlayerPrefs.SetInt(Constants.optSFX, 1);
//		PlayerPrefs.SetInt(Constants.optMusic, 1);
//		
//		PlayerPrefs.SetString("DMOIsNewUser",null);
//		PlayerPrefs.SetString("DMOCurrentUniqueID",null);
//	}
//
//	public void GetUserClub()
//	{
//		Debug.Log("tempBolaUser CLUB: "+ (tempBolaUser.Club != null));
//		tempBolaUser.Save();
//		
//		Directory.Delete (Application.persistentDataPath+ "/Transactions/", true);
//		SceneLoader.Instance.LoadScene (Constants.SCENE_MAIN_MENU);
//	}
//	
//	private void PostNewUserClub()
//	{
//		#if UNITY_IPHONE || UNITY_ANDROID
//		Debug.Log ("PostNewUserClub");
//		SendFacebookUserIDtoOtherUser(tempBolaUser.gameID, tempBolaUser.userToken, tempBolaUser.gameID+"_old");
//		#endif
//	}	
//	private void SendFacebookUserIDtoOtherUser(string GameId, string UserToken, string faceID)
//	{
//		GenericPopup.Instance.ShowPopupOk("PopupMessagePostUser", ()=>{}, false);
//		
//		if(Application.internetReachability != NetworkReachability.NotReachable)
//		{
//			httpClient.Send (RequestFactory.SetFaceUserRequest(GameId, UserToken, faceID) ) 
//				.SetCompleteHandler(www => {
//					if(!www.TestEmptyResponse(www.text))
//					{
//						Debug.Log ("FACE ID POSTED:"+ www.text);
//						
//						#if UNITY_IPHONE || UNITY_ANDROID
//						
//						bolaUser.SetFacebookID(facebookController._Me.id);
//						SendFacebookUserID(facebookController._Me.id);
//						#endif
//						UserPostSuccess(faceID);
//						
//					}else{
//						UserPostFail();
//					}
//				})
//					.SetErrorHandler(www => { 
//						Debug.Log("FACEPOST  WWW error: "+www.error);
//						UserPostFail();
//					} 
//					);
//		}else{
//			UserPostFail();
//		}
//	}
//	public void UpdateFacebookVisual()
//	{
//		#if UNITY_IPHONE || UNITY_ANDROID
//
//		if (facebookController.GetFriendsCount () > 0)
//		{
//			pvpScreen.ShowOpponentsArrows(false);
//			if (facebookController.GetFriendsCount () > 1)
//			{
//				pvpScreen.ShowOpponentsArrows(true);
//				Debug.Log("Entro 0");
//			}
//			pvpScreen.buttonConnect.SetActive(false);
//			pvpScreen.lblOpponent.gameObject.SetActive (true);				
//			pvpScreen.friendPic.gameObject.SetActive(true);
//			pvpScreen.noTeamSelected.gameObject.SetActive(false);
//			GenericPopup.Instance.HidePopup ();
//			Debug.Log("Entro 1");
//		}
//		else
//		{
//			pvpScreen.buttonConnect.SetActive(true);
//			pvpScreen.ShowOpponentsArrows(false);
//			pvpScreen.lblOpponent.gameObject.SetActive (false);				
//			pvpScreen.friendPic.gameObject.SetActive(false);
//            GenericPopup.Instance.HidePopup();
//			pvpScreen.noTeamSelected.gameObject.SetActive(true);
//			Debug.Log("Entro 2");
//		}
//		#endif
//	}
//	public void GetNextFacebookTeam()
//	{
//		#if UNITY_IPHONE || UNITY_ANDROID
//		if (facebookController.IsLogged())
//		{
//			Debug.Log("FaceNextTeam");			
//			FacebookAppFriend myFriend = facebookController.GetNextFriend ();
//			if (myFriend != null )
//			{
//				pvpScreen.lblOpponent.text = myFriend.name;
//				GetFacebookTeam(myFriend.id);
//				pvpScreen.friendPic.LoadLocalImage("facebookFriends", myFriend.id, "https://graph.facebook.com/"+ myFriend.id +"/picture?width=300&height=300",true, 10); 
//				pvpScreen.buttonConnect.SetActive(false);
//			}
//			else{	
//				if (pvpScreen.GetCategory () == PVPScreen.Categories.Friends)
//					GenericPopup.Instance.ShowPopupOk("NoFacebookFriends", CloseNoFriendsPopup, true);
//			}
//		}
//		else
//		{
//			GenericPopup.Instance.ShowPopupOk("NotLoggedFacebook", () => {}, true);
//		}
//		#endif
//	}
//	public void GetPrevFacebookTeam()
//	{
//		#if UNITY_IPHONE || UNITY_ANDROID
//		if (facebookController.IsLogged())
//		{
//			Debug.Log("FacePrevTeam");
//			FacebookAppFriend myFriend = facebookController.GetPrevFriend ();
//			if (myFriend != null)
//			{
//				pvpScreen.lblOpponent.text = myFriend.name;
//				pvpScreen.friendPic.LoadLocalImage("facebookFriends", myFriend.id, "https://graph.facebook.com/"+ myFriend.id +"/picture?width=300&height=300",true, 10);
//				pvpScreen.buttonConnect.SetActive(false);
//				GetFacebookTeam(myFriend.id);
//			}
//			else{		
//				if (pvpScreen.GetCategory () == PVPScreen.Categories.Friends)		
//					GenericPopup.Instance.ShowPopupOk("NoFacebookFriends", CloseNoFriendsPopup, true);
//			}
//		}
//		else
//		{
//			GenericPopup.Instance.ShowPopupOk("NotLoggedFacebook", () => {}, true);
//		}
//		#endif
//	}
//	
//	private bool LoggingIn;
//	public void FacebookLogIn()
//	{
//		if (LoggingIn)
//			return;
//		#if UNITY_IPHONE || UNITY_ANDROID
//		if (Application.internetReachability != NetworkReachability.NotReachable)
//		{		
//			if (facebookController.IsLogged())
//			{
//				facebookController._Me = null;
//				facebookController.ClearFriends ();
//				facebookController.LogOut ();
//			}
//			if (!facebookController.IsLogged())
//			{
//				LoggingIn = true;
//				Debug.Log("LOG INNN");
//				//GenericPopup.Instance.ShowPopupOk("FacebookUserCheck", ()=>{}, false);
//
//				facebookController.LogIn ();
//
//				FacebookManager.CleanLogInActions ();
//				FacebookManager.sessionOpenedEvent += SuccesLogInCallback;
//				FacebookManager.loginFailedEvent += FailedLogInCallback;
//			}
//			else
//			{				
//				Debug.Log("CANT LOG INNN" + (!facebookController.IsLogged()) + " || " + (!pvpScreen.IsConectedForApp));
//			}
//		}
//		else
//		{
//			GenericPopup.Instance.ShowPopupOk("NoInternet", () => {}, true);
//		}
//		#endif
//	}
//	public void FacebookLogOut()
//	{
//		#if UNITY_IPHONE || UNITY_ANDROID
//		if (Application.internetReachability != NetworkReachability.NotReachable)
//		{
//			if (facebookController.IsLogged())
//			{
//				facebookController.LogOut ();
//			}
//		}
//		else
//		{
//			GenericPopup.Instance.ShowPopupOk("NoInternet", () => {}, true);
//		}
//		#endif
//	}
//
//	
//	private RewardsModel RewardScalator(RewardsModel baseReward, float difficultyMultiplier, float resultMultiplier)
//	{
//		int xpReward = baseReward.Xp;
//		int bollarsReward = baseReward.Bolars;
//		int goldReward = baseReward.Gold;
//		
//		xpReward = Mathf.RoundToInt(baseReward.Xp * difficultyMultiplier * resultMultiplier);
//		bollarsReward = Mathf.RoundToInt(baseReward.Bolars * difficultyMultiplier * resultMultiplier);
//		goldReward = Mathf.RoundToInt(baseReward.Gold * difficultyMultiplier * resultMultiplier);
//		
//		string rewardString = "bolars:" + bollarsReward + ";gold:" + goldReward + ";xp:" + xpReward;
//
//		Debug.Log ("Reward - Bollars: " + baseReward.Bolars + "/" + bollarsReward + " - Gold:" + baseReward.Gold + "/" + goldReward);
//
//		RewardsModel newReward = new RewardsModel (rewardString);
//		return newReward;
//	}
//
//	private float GetRewardDifficultyMultiplier(int UserXP, int OpponentXP)
//	{
//		int minDiff = 0;
//		int maxDiff = 0;
//
//		foreach (IPvPRewardModel reward in pvpRewardCatalog.PvPRewards) 
//		{
//			if(reward.LevelDifference < minDiff)
//				minDiff = reward.LevelDifference;
//			if(reward.LevelDifference > maxDiff)
//				maxDiff = reward.LevelDifference;
//		}
//
//		int levelDiff =  UserXP - OpponentXP;
//		
//		if (Mathf.Abs (levelDiff) > maxDiff) 
//			levelDiff = levelDiff > 0 ? maxDiff : minDiff; 
//
//		float multiplier = 1;
//
//		foreach (IPvPRewardModel reward in pvpRewardCatalog.PvPRewards) 
//			if(reward.LevelDifference == levelDiff)
//				multiplier = reward.RewardPercentage;
//
//		Debug.Log("PVP >> UserXP: "+ UserXP +" OpponentXP: "+OpponentXP+" diff: "+levelDiff+" multiplier: "+multiplier);
//		
//		return multiplier;
//	}
//}